import os
import time
import pandas as pd


import pyecharts.options as opts
from pyecharts.faker import Faker
from pyecharts.charts import Line
from pyecharts.charts import Pie
from pyecharts.charts import BMap


import PySide2
from PySide2.QtWidgets import QApplication, QMessageBox, QFileDialog
from PySide2.QtUiTools import QUiLoader


# 环境问题，重要！！
dirname = os.path.dirname(PySide2.__file__)
plugin_path = os.path.join(dirname, 'plugins', 'platforms')
os.environ['QT_QPA_PLATFORM_PLUGIN_PATH'] = plugin_path


class VisualExe:

    def __init__(self):
        # 从UI定义中动态 创建一个相应的窗口对象
        # 注意：里面的控件对象也成为窗口对象的属性了
        # 比如self.ui.button, self.ui.textEdit
        loader = QUiLoader()
        self.ui = loader.load(r'./ui/visual.ui')
        self.ui.line_button.clicked.connect(self.handle_line)
        self.ui.pie_button.clicked.connect(self.handle_pie)
        self.ui.map_button.clicked.connect(self.handle_map)
        self.error = None

    def log(self, msg):
        now = time.strftime("%Y-%m-%d %H:%M:%S")
        event = now + ": " + msg
        self.ui.log.append(event)

    def handle_line(self):
        file_path, _ = QFileDialog.getOpenFileName(self.ui, "选择你要上传的文件", os.getcwd(), "Excel文件 (*.xls *.xlsx)")
        if file_path:
            try:
                self.error = "获取文件名称"
                file_name = file_path[file_path.rindex("/") + 1: file_path.rindex(".")]

                self.log("读取Excel文件")
                self.error = "Excel文件读取"
                df = pd.read_excel(file_path)
                self.log("读取成功")

                self.log("检查输入数据")
                self.error = "数据格式"
                self.log("检查通过")

                self.log("按日期排序")
                df.sort_values(by=df.columns[0], inplace=True)  # 按日期排序
                self.log("排序成功")
                x = [i.date() for i in df.iloc[:, 0].to_list()]
                y = df.iloc[:, 1].to_list()

                self.log("绘图")
                self.error = "pyecharts绘图"
                c = (
                    Line()
                        .add_xaxis(x)
                        .add_yaxis("医院A", y)
                        .set_global_opts(title_opts=opts.TitleOpts(title="Line-基本示例"))
                        .render(os.getcwd() + "\\" + file_name + ".html")
                )
                self.log("绘图完毕")

                choice = QMessageBox.question(self.ui, '确认', '要打开图片吗？')
                if choice == QMessageBox.Yes:
                    self.log("打开图像")
                    os.system(c)
                    self.log("打开成功")
                else:
                    self.log("选择不打开图像")
            except:
                self.log("出错了，请检查" + self.error)
                # QMessageBox.critical(self.ui, "Error", "出错了，请检查" + self.error)

    def handle_pie(self):
        c = (
            Pie()
                .add("", [list(z) for z in zip(Faker.choose(), Faker.values())])
                .set_global_opts(title_opts=opts.TitleOpts(title="Pie-基本示例"))
                .set_series_opts(label_opts=opts.LabelOpts(formatter="{b}: {c}"))
                .render(os.getcwd() + "\\" + "pie_base.html")
        )

        choice = QMessageBox.question(self.ui, '确认', '要打开图片吗？')
        if choice == QMessageBox.Yes:
            os.system(c)

    def handle_map(self):
        c = (
            BMap()
                .add_schema(baidu_ak="FAKE_AK", center=[120.13066322374, 30.240018034923])
                .add(
                "bmap",
                [list(z) for z in zip(Faker.provinces, Faker.values())],
                label_opts=opts.LabelOpts(formatter="{b}"),
            )
                .set_global_opts(title_opts=opts.TitleOpts(title="BMap-基本示例"))
                .render(os.getcwd() + "\\" + "bmap_base.html")
        )

        choice = QMessageBox.question(self.ui, '确认', '要打开图片吗？')
        if choice == QMessageBox.Yes:
            os.system(c)


app = QApplication([])
stats = VisualExe()
stats.ui.show()
app.exec_()
